import { useMemberStore } from "@/stores";

const baseUrl = 'https://pcapi-xiaotuxian-front.itheima.net'

const httpInterceptor = {
    invoke(options: UniApp.RequestOptions) {

        // 非http请求开头需拼接地址
        if (!options.url.startsWith('http')) {
            options.url = baseUrl + options.url;
        }
        options.timeout = 10000;
        options.header = {
            ...options.header,
            'source-client': 'miniapp'
        }

        const memberStore = useMemberStore()
        const token = memberStore.profile?.token
        if (token && !options.url.endsWith('goods')) {
            options.header.Authorization = token
        }
    }
}

uni.addInterceptor('request', httpInterceptor)
uni.addInterceptor('uploadFile', httpInterceptor)

interface Data<T> {
    code: string,
    msg: string,
    result: T
}

export const http = <T>(options: UniApp.RequestOptions) => {
    return new Promise<Data<T>>((resolve, reject) => {
        uni.request({
            ...options,
            success(res) {
                if (res.statusCode >= 200 && res.statusCode < 300) {
                    // 请求成功，提取核心数据
                    resolve(res.data as Data<T>)
                } else if (res.statusCode === 401) {
                    // 401 -> 清理用户信息，跳转到登录页面
                    const memberStore = useMemberStore()
                    memberStore.clearProfile
                    uni.navigateTo({ url: '/pages/login/login' })
                    reject(res)
                } else {
                    // 其他错误 -> 根据后端提示信息进行提示
                    uni.showToast({
                        icon: 'none',
                        title: (res.data as Data<T>).msg || '请求错误'
                    })
                    reject(res)
                }
            },
            fail(err) {
                // 网络错误，直接提示
                uni.showToast({
                    title: '网络错误，请换个网络试试',
                    icon: 'none',
                })
                reject(err)
            }
        })
    })
}